<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog
    v-model="visible"
    :loading="loading"
    :title="`${dataId ? '编辑' : '创建'}`"
    :width="540"
    @submit="submit"
    @cancel="cancel"
  >
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="100">
      <FormItem label="分类名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入名称" />
      </FormItem>

      <FormItem label="上级分类">
        <el-tree-select
          v-model="formData.parentid"
          :data="props.treeData"
          :render-after-expand="false"
          teleported
          default-expand-all
          filterable
          placeholder="请选择上级分类"
          node-key="id"
          :expand-on-click-node="false"
          :props="{
            children: 'children',
            label: 'name'
          }"
        />
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { ref, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { faq } from '@/api/modules/knowledgeBase'
import { modelManage } from '@/api/modules/modelSetting'

import { ElTreeSelect } from 'element-plus'

const emit = defineEmits(['cancel', 'submit'])
const getTypeId = inject('getTypeId')
const props = defineProps({
  treeData: Array
})

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: '', //名称
  parentid: 0
})

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }]
})

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const params = {
      ...formData.value,
      id: dataId.value,
      typeid: getTypeId()
    }

    await faq[dataId.value ? 'typeEdit' : 'typeAdd']({
      data: params
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

/**
 * 初始化对话框
 */
const initDialog = (data) => {
  // 显示对话框
  visible.value = true

  dataId.value = data?.id

  if (dataId.value) {
    for (const key in formData.value) {
      if(key === 'parentid') {
        formData.value[key] = data[key] === '0' ? 0 : data[key]
        continue
      }

      formData.value[key] = data[key]
    }
  }
}

defineExpose({
  initDialog
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select,
.el-select {
  width: 360px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>
